package com.zhudao.crawler.util;

import jodd.http.HttpRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Http工具类
 * Created by wangnian on 2016/6/2.
 */
public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * get请求
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        String strResult = HttpRequest.get(url).send().bodyText();
        return  strResult;
    }

    /**
     * 带参数的get请求
     *
     * @param url
     * @param parMap
     * @return
     */
    public static String get(String url, Map<String, String> parMap) {
        HttpRequest httpRequest = HttpRequest.get(url);
        httpRequest.query(parMap);
        String strResult = httpRequest.send().bodyText();
        logger.info("url:{},parMap:{},response:{}", url, httpRequest.query(), StringUtils.trim(strResult));
        return strResult;
    }

    /**
     * 带参数post请求
     *
     * @param url
     * @return
     */
    public static String post(String url, Map<String, String> parMap) {
        HttpRequest httpRequest = HttpRequest.post(url);
        httpRequest.query(parMap);
        String strResult = httpRequest.send().bodyText();
        logger.info("url:{},parMap:{},response:{}", url, httpRequest.query(), StringUtils.trim(strResult));
        return strResult;
    }


    /**
     * RAW Post请求
     *
     * @param url
     * @param Body
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String post(String url, String Body) {
        HttpRequest httpRequest = HttpRequest.post(url);
        httpRequest.bodyText(Body);
        String strResult = httpRequest.send().bodyText();
        logger.info("url:{},Body:{},response:{}", url, Body, StringUtils.trim(strResult));
        return strResult;
    }


}
